package com.okhttp;

import android.util.Log;

import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by mk on 2017/10/28.
 */

public class MyHttpUtils {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private OkHttpClient client;
//    private IMyHttpUtilsCallback utilsCallback;

    public MyHttpUtils() {
        client = new OkHttpClient();
    }

    public String Post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        String result = response.body().string();


        return result;
    }


    public String Get(String url) throws IOException {

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = client.newCall(request).execute();

        String result = response.body().string();

        return result;
    }

    public void PostCommonAsync(String url, String json,String token, IMyHttpUtilsCallback listener) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(url)
                .header("token",token)
                .post(body)
                .build();

        Call call = client.newCall(request);
        call.enqueue(creatCallback(listener));
    }

    public void PostAsync(String url, String json,String token, DGRequestListener listener) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(url)
                .header("token",token)
                .post(body)
                .build();

        Call call = client.newCall(request);
        call.enqueue(creatCallback(listener));
    }

    public void GetAsync(String url, final DGRequestListener listener) throws IOException {

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Call call = client.newCall(request);
        call.enqueue(creatCallback(listener));
    }

    public void GetCommonAsync(String url,String token, final IMyHttpUtilsCallback listener) throws IOException {
        Request request;
        if(token != null && token.length()>0){
            request = new Request.Builder()
                    .url(url)
                    .header("token",token)
                    .get()
                    .build();
        }else {
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        }
        Call call = client.newCall(request);
        call.enqueue(creatCallback(listener));
    }

    public void DeleteAsync(String url, String token, final DGRequestListener listener) throws IOException {
        Request request;
        if(token != null && token.length()>0){
            request = new Request.Builder()
                    .url(url)
                    .header("token",token)
                    .delete()
                    .build();
        }else {
             request = new Request.Builder()
                    .url(url)
                    .delete()
                    .build();
        }
        Call call = client.newCall(request);
        call.enqueue(creatCallback(listener));
    }

    private Callback creatCallback(final DGRequestListener listener) {
        return new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                DGJsonResult myResponse = new DGJsonResult();

                if (response.isSuccessful()) {
                    if (myResponse.isSuccess(res)) {
                        myResponse.errorCode = DGJsonResult.REQUEST_SUCCESS;
                        listener.onSuccess(myResponse);
                    } else {
                        myResponse.errorCode = DGJsonResult.REQUEST_ERROR;
                        JSONObject jsonObject;
                        String errorMsg;
                        try {
                            jsonObject = new JSONObject(myResponse.result);
                            errorMsg = jsonObject.getString("errorMsg");
                        } catch (JSONException e) {
                            errorMsg = "";
                            e.printStackTrace();
                        }

                        listener.onError(errorMsg);
                    }
                } else {
                    listener.onError("error code:" + response.code());
                }
            }
        };
    }

    private Callback creatCallback(final IMyHttpUtilsCallback listener) {
        return new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFailure(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    listener.onResponse(response.body().string());
                } else {
                    listener.onFailure("error code:" + response.code());
                }
            }
        };
    }

    public interface IMyHttpUtilsCallback {
        void onFailure(String errorMsg);

        void onResponse(String response);
    }

}
